package org.jeecg.modules.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pz.cloud.framework.base.dao.CommonDao;
import com.pz.cloud.framework.base.model.Pageable;
import com.pz.cloud.framework.business.workflow.entity.TaskNodeAttr;
import com.pz.cloud.framework.business.workflow.entity.TaskNodeHandlerRule;
import com.pz.cloud.framework.business.workflow.enums.WorkflowEnum;
import com.pz.cloud.framework.business.workflow.model.TaskUserModel;
import com.pz.cloud.framework.business.workflow.service.ITaskNodeAttrService;
import com.pz.cloud.framework.model.SqlBuilder;
import com.pz.cloud.framework.util.BizUtil;
import com.pz.cloud.framework.util.SqlUtil;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.system.vo.TreeNode;
import org.jeecg.common.util.TreeNodeUtil;
import org.jeecg.common.util.UUIDUtils;
import org.jeecg.modules.system.model.DepartIdModel;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserDepart;
import org.jeecg.modules.system.mapper.SysUserDepartMapper;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.vo.SysUserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.CollectionUtils;

import javax.persistence.Query;

/**
 * <P>
 * 用户部门表实现类
 * <p/>
 * @Author ZhiLin
 *@since 2019-02-22
 */
@Service
public class SysUserDepartServiceImpl extends ServiceImpl<SysUserDepartMapper, SysUserDepart> implements ISysUserDepartService {
	@Autowired
	private ISysDepartService sysDepartService;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ITaskNodeAttrService taskNodeAttrService;
	@Autowired
	private CommonDao commonDao;

	/**
	 * 根据用户id查询部门信息
	 */
	@Override
	public List<DepartIdModel> queryDepartIdsOfUser(String userId) {
		LambdaQueryWrapper<SysUserDepart> queryUDep = new LambdaQueryWrapper<SysUserDepart>();
		LambdaQueryWrapper<SysDepart> queryDep = new LambdaQueryWrapper<SysDepart>();
		try {
			queryUDep.eq(SysUserDepart::getUserId, userId);
			List<String> depIdList = new ArrayList<>();
			List<DepartIdModel> depIdModelList = new ArrayList<>();
			List<SysUserDepart> userDepList = this.list(queryUDep);
			if(userDepList != null && userDepList.size() > 0) {
			for(SysUserDepart userDepart : userDepList) {
					depIdList.add(userDepart.getDepId());
				}
			queryDep.in(SysDepart::getId, depIdList);
			List<SysDepart> depList = sysDepartService.list(queryDep);
			if(depList != null || depList.size() > 0) {
				for(SysDepart depart : depList) {
					depIdModelList.add(new DepartIdModel().convertByUserDepart(depart));
				}
			}
			return depIdModelList;
			}
		}catch(Exception e) {
			e.fillInStackTrace();
		}
		return null;
		
		
	}
	/**
	 * 根据用户id查询部门信息
	 */
	@Override
	public List<SysUserDepart> queryUserDepartByUserId(String userId) {
		LambdaQueryWrapper<SysUserDepart> queryUDep = new LambdaQueryWrapper<>();
		queryUDep.eq(SysUserDepart::getUserId, userId);
		List<SysUserDepart> userDepList = this.list(queryUDep);
		return userDepList;
	}
	/**
	 * 根据用户id查询部门信息
	 */
	@Override
	public List<SysUserDepart> queryUserDepartByDepIds(List<String> depIds) {
		LambdaQueryWrapper<SysUserDepart> queryUDep = new LambdaQueryWrapper<>();
		queryUDep.in(SysUserDepart::getDepId, depIds);
		List<SysUserDepart> userDepList = this.list(queryUDep);
		return userDepList;
	}


	/**
	 * 根据部门id查询用户信息
	 */
	@Override
	public List<SysUser> queryUserByDepId(String depId) {
		LambdaQueryWrapper<SysUserDepart> queryUDep = new LambdaQueryWrapper<SysUserDepart>();
		queryUDep.eq(SysUserDepart::getDepId, depId);
		List<String> userIdList = new ArrayList<>();
		List<SysUserDepart> uDepList = this.list(queryUDep);
		if(uDepList != null && uDepList.size() > 0) {
			for(SysUserDepart uDep : uDepList) {
				userIdList.add(uDep.getUserId());
			}
			List<SysUser> userList = (List<SysUser>) sysUserService.listByIds(userIdList);
			//update-begin-author:taoyan date:201905047 for:接口调用查询返回结果不能返回密码相关信息
			for (SysUser sysUser : userList) {
				sysUser.setSalt("");
				sysUser.setPassword("");
			}
			//update-end-author:taoyan date:201905047 for:接口调用查询返回结果不能返回密码相关信息
			return userList;
		}
		return new ArrayList<SysUser>();
	}

	/**
	 * 根据部门code，查询当前部门和下级部门的 用户信息
	 */
	@Override
	public Page<SysUserVo> queryUserByDepCode(TaskUserModel taskUserModel) {
		List<String> depIds = new ArrayList<>();
		List<String> userIds = new ArrayList<>();
		if(!StringUtils.isEmpty(taskUserModel.getDepCode())){
			LambdaQueryWrapper<SysDepart> queryByDepCode = new LambdaQueryWrapper<>();
			queryByDepCode.likeRight(SysDepart::getOrgCode,taskUserModel.getDepCode());
			List<SysDepart> sysDepartList = sysDepartService.list(queryByDepCode);
			depIds = sysDepartList.stream().map(SysDepart::getId).collect(Collectors.toList());
		}

		if(StringUtils.isNotEmpty(taskUserModel.getTaskKey())){
			TaskNodeAttr taskNodeAttr = taskNodeAttrService.getById(taskUserModel.getTaskKey());

			if (taskNodeAttr != null) {
				List<TaskNodeHandlerRule> handlerRuleList = taskNodeAttr.getHandlerRuleList();
				if(!CollectionUtils.isEmpty(handlerRuleList)){
					for (TaskNodeHandlerRule rule : handlerRuleList) {
						String handlerType = rule.getHandlerType();
						String ruleHandlerValue = rule.getHandlerValue();
						String handlerDeptId = rule.getHandlerDeptId();
						if(StringUtils.isEmpty(ruleHandlerValue)){
							continue;
						}
						if (handlerType.equals(WorkflowEnum.TaskNodeHandlerType.用户.getType())) {
							String[] uIds = ruleHandlerValue.split(",");

							List<String> list = findUserIds(depIds, Arrays.asList(uIds));
							if(!CollectionUtils.isEmpty(list)){
								userIds.addAll(list);
							}
						} else if (handlerType.equals(WorkflowEnum.TaskNodeHandlerType.部门.getType())) {
							String[] dIds = ruleHandlerValue.split(",");
							List<String> dList = new ArrayList<>();
							for (String dId : dIds) {
								dList.add(dId);
							}
							if(!CollectionUtils.isEmpty(depIds)){
								depIds.retainAll(dList);
							}else{
								depIds.addAll(dList);
							}
						} else if (handlerType.equals(WorkflowEnum.TaskNodeHandlerType.角色.getType())) {
							String[] roleIds = ruleHandlerValue.split(",");
							List<SysUser> sysUsers = sysUserService.getUserByRoleIds(Arrays.asList(roleIds));
							if(!CollectionUtils.isEmpty(sysUsers)){
								sysUsers.forEach(sysUser->userIds.add(sysUser.getId()));
							}

						} else if (handlerType.equals(WorkflowEnum.TaskNodeHandlerType.职务.getType())) {
							String[] postCode = ruleHandlerValue.split(",");
							List<SysUser> sysUsers = sysUserService.getUserByPostCodes(Arrays.asList(postCode));
							if(!CollectionUtils.isEmpty(sysUsers)){
								sysUsers.forEach(sysUser->userIds.add(sysUser.getId()));
							}

						} else if (handlerType.equals(WorkflowEnum.TaskNodeHandlerType.部门内角色.getType())) {
							String[] roleIds = ruleHandlerValue.split(",");
							//如果无值，默认查当期登录部门
							List<String> deptIds = BizUtil.getUser().getDeptIdList();
							if(!org.springframework.util.StringUtils.isEmpty(handlerDeptId)){
								deptIds =  Arrays.asList(handlerDeptId.split(","));
							}
							List<SysUser> sysUsers = sysUserService.getListByRoleIdsAndDeptIds(Arrays.asList(roleIds),deptIds );
							if(!CollectionUtils.isEmpty(sysUsers)){
								sysUsers.forEach(sysUser->userIds.add(sysUser.getId()));
							}

						}else if (handlerType.equals(WorkflowEnum.TaskNodeHandlerType.部门内职务.getType())) {
							String[] postCodes = ruleHandlerValue.split(",");
							//如果无值，默认查当期登录部门
							List<String> deptIds = BizUtil.getUser().getDeptIdList();
							if(!org.springframework.util.StringUtils.isEmpty(handlerDeptId)){
								deptIds =  Arrays.asList(handlerDeptId.split(","));
							}
							List<SysUser> sysUsers = sysUserService.getListByPostCodesAndDeptIds(Arrays.asList(postCodes),deptIds );
							if(!CollectionUtils.isEmpty(sysUsers)){
								sysUsers.forEach(sysUser->userIds.add(sysUser.getId()));
							}

						}
					}
				}
			}
		}

//		if(CollectionUtils.isEmpty(userIds)){
//			if(!CollectionUtils.isEmpty(depIds)){
//				List<String> list = findUserIds(depIds,null);
//				if(!CollectionUtils.isEmpty(list)){
//					userIds.addAll(list);
//				}
//			}
//		}
		List<String> uList = userIds.stream().distinct().collect(Collectors.toList());
		List<String> dList = depIds.stream().distinct().collect(Collectors.toList());
		Page<SysUserVo> page = sysUserService.userList(taskUserModel, uList,dList);
		for (SysUserVo vo1 : page.getRecords()) {
			vo1.setSalt("");
			vo1.setPassword("");
		}
		return page;
	}

	private List<String> findUserIds(List<String> depIds,List<String> userIds){
		StringBuilder sql = new StringBuilder("select distinct(user_id) uid from sys_user_depart where 1=1 ");
		Map<String,Object> params = new HashMap<>();
		if(!CollectionUtils.isEmpty(depIds)){
			sql.append(" and dep_id in (:depIds)");
			params.put("depIds",depIds);
		}
		if(!CollectionUtils.isEmpty(userIds)){
			sql.append(" and user_id in (:userIds)");
			params.put("userIds",userIds);
		}

		Query query = commonDao.getEntityManager().createNativeQuery(sql.toString());
		SqlUtil.setQueryParams(params,query);
		List resultList = query.getResultList();
		return resultList;
	}
//	/**
//	 * 根据部门code，查询当前部门和下级部门的 用户信息
//	 */
//	@Override
//	public List<SysUserVo> queryUserByDepCode(String depCode,SysUserVo sysUserVo) {
//		List<String> depIds = null;
//		if(!StringUtils.isEmpty(depCode)){
//			LambdaQueryWrapper<SysDepart> queryByDepCode = new LambdaQueryWrapper<SysDepart>();
//			queryByDepCode.likeRight(SysDepart::getOrgCode,depCode);
//			List<SysDepart> sysDepartList = sysDepartService.list(queryByDepCode);
//			depIds = sysDepartList.stream().map(SysDepart::getId).collect(Collectors.toList());
//		}
//
//		LambdaQueryWrapper<SysUserDepart> queryUDep = new LambdaQueryWrapper<SysUserDepart>();
//		if(depIds!=null){
//			queryUDep.in(SysUserDepart::getDepId, depIds);
//		}
//		List<String> userIdList = new ArrayList<>();
//		List<SysUserDepart> uDepList = this.list(queryUDep);
//		if(uDepList != null && uDepList.size() > 0) {
//			for(SysUserDepart uDep : uDepList) {
//				userIdList.add(uDep.getUserId());
//			}
//
////			List<SysUser> userList = (List<SysUser>) sysUserService.list(queryUser);
//			List<SysUserVo> userVoList = sysUserService.userList(sysUserVo, userIdList);
//			//update-begin-author:taoyan date:201905047 for:接口调用查询返回结果不能返回密码相关信息
////			for (SysUser sysUser : userList) {
////				sysUser.setSalt("");
////				sysUser.setPassword("");
////			}
//			for (SysUserVo vo1 : userVoList) {
//				vo1.setSalt("");
//				vo1.setPassword("");
//			}
//
//
//			//update-end-author:taoyan date:201905047 for:接口调用查询返回结果不能返回密码相关信息
//			return userVoList;
//		}
//		return new ArrayList<SysUserVo>();
//	}
}
